/**
 * 功能：转账
 * 入口：转入公司账户
 * 
 */
import React from 'react'
import PureRenderMixin from 'react-addons-pure-render-mixin'
import {Alert,PullLoad,Header} from 'components/index'
import FormInput from 'components/FormInput/index.jsx'
import {DanluJsBridge,filter,logger,http} from 'common/index'
import {CheckPassword,Caption} from './subpage/index'
import { Link,hashHistory,browserHistory } from 'react-router';
import Enume from './enume'

// redux
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as walletInfoActionsFromOtherFile from '../../store/actions/walletinfo' 


class Transfer extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
        this.state = {
            password : '', //支付密码
            havePassword : false, //是否已经设置支付密码
            showCheckPasswd : false,
            isTransfered : false,
            balance : {} ,
            errorInfo : '',
            amount : '', //转账金额
            transferDisabled: true
        }
    }
    componentWillMount (){
        DanluJsBridge.callHandler('setTitle', {
                title: '转账',
                color: '#ffffffff',
            }, function(response) {
        })
        var _this = this;
        
        //是否设置过支付密码
        this.setState({
            havePassword: this.props.walletinfo.havePassword || true
          });
    }
    
    amountChange (value){
        var errorInfo = ''
        var transferDisabled = false
        if (!parseFloat(value)) {
            errorInfo = "请输入金额";
            transferDisabled = true
        }else if (parseFloat(value)<0) {
            errorInfo = "金额格式不正确";
            transferDisabled = true
        }else if(value.split(".").length>1 && value.split(".")[1].length >2){
            errorInfo = '仅支持小数点后两位'
            transferDisabled = true
        }else if(this.state.balance.avl_bal - value*100 < 0){
            errorInfo = '金额不可超过可用余额';
            transferDisabled = true
        }

        this.setState({
            amount : value,
            errorInfo :errorInfo,
            transferDisabled :transferDisabled
        })
    }
    ValidatePassword (){
        this.setState({
            showCheckPasswd : true
        })
    }
    //查询余额
    getBalance (){
        var _this = this;
        return new Promise(function(resolve,reject){
             var reqData = {
                "userId": _this.props.walletinfo.user.userId,
                "companyId": _this.props.walletinfo.user.companyId
            }
            http.post('/dlpcweb/dlpc/pc/V1/wallet/getBalance',reqData).then((data) =>{
                var balanceDetail = data.balanceDetail || []
                _this.props.walletinfoActions.walletInfoUpdate({
                    balanceDetail : balanceDetail,
                    withDrawFee : data.withDrawFee
                })
                resolve();
            }).catch(function(e){
                resolve();
            })           
        })
    }
    //转账金额限制规则
    moneyChangeRule (value){

        // 限制小数点两位
        if (value && value.indexOf('.')>0 ) {
            var decimals = value.split('.')[1];
            // 保留小数点后两位
            if (decimals.length >2) {
                value =  parseInt(value*100)/100
            }
        }
        // 限制长度
        if (value.toString().length >12) {
            value = value.substring(0,12)
        }
        return value.toString()
    }
    //确认转账
    sureTransfer (){
        var _this = this;
        this.setState({
            transferDisabled : true,
            showCheckPasswd : false,
        })
        var reqData = {
            "userId": this.props.walletinfo.user.userId,
            "companyId": this.props.walletinfo.user.companyId,
            "amount": (this.state.amount*100).toString(),
        }
        http.post('/dlpcweb/dlpc/pc/V1/wallet/transfer',reqData).then( data => {

            // 转账申请成功
            this.setState({
                isTransfered : true
            })
        }).catch(function(err){
            _this.getBalance();
            _this.setState({
                amount : '',
                transferDisabled : true
            })
        })
    }
    //转账完成
    completeTransfer (){

        this.setState({
            isTransfered : false,
            showCheckPasswd : false
        })

    }
    //取消
    cancel (){
        this.setState({
            showCheckPasswd : false
        })
    }
    // 返回上一级
    goBack(){
        browserHistory.goBack()
    }
    render() {
        var balanceDetail= this.props.walletinfo.balanceDetail || []
        var balance = ""
        balanceDetail.map(item =>{
            if (item.acc_type ==  this.props.location.state.acc_type) {
                balance =  item
            }
        })
        this.state.balance = balance
        
        return (
        	<div className="Transfer">
        		<Header title="转账" className="wallet-hader"/>
                {/* 弹窗 */}
                {
                    this.state.showCheckPasswd == true ? (
                        <CheckPassword havePassword={this.state.havePassword} validate={this.sureTransfer.bind(this)} cancel={this.cancel.bind(this)} userId={this.props.walletinfo.user.userId}/>
                    ) : ''
                }
                <div className="wallet-hader">
                    <div className="align-center wallet-account">
                        <div className="inline-block TranItem"  >
                            <img src={require('static/image/wallet-person.png')} alt="" />
                        </div>
                        <div className="inline-block TranItem"  >
                            <img src={require('static/image/wallet-transfer.png')} alt="" />
                        </div>
                        <div className="inline-block TranItem"  >
                            <img src={require('static/image/wallet-company.png')} alt="" />
                        </div>
                    </div>
                    <div className="align-center padding10">个人账户转至公司账户</div>
                </div>

            {/*  判断是否转账完成     */}
                {
                    this.state.isTransfered === true ? (
                        <div>
                            <div className="padding10" style={{background:'#fff'}}>
                                <span>转账申请已提交，请等待处理结果</span>
                            </div>
                            <div className="padding10" style={{borderTop:'1px solid lightgray',background:'#fff'}}>
                                <div>
                                    <span>明细：个人账户向公司账户转账</span>
                                </div>
                                <div>
                                    <span>金额：</span><span style={{color:'#fc7646'}}>¥ {filter.toMoneyFormat(this.state.amount*100)}元</span>
                                </div>
                            </div>

                            <div className="complete-btn">
                                <button className="sure-btn " onClick={this.goBack.bind(this)}> 完 成 </button>
                            </div>
                        </div>
                    ) : (
                        <div>
                            <div >
                                <FormInput placeholder="请输入转账金额 " type="number" changeRule={this.moneyChangeRule.bind(this)} value={this.state.amount} onChange={this.amountChange.bind(this)}/>
                                {
                                    this.state.errorInfo ? (
                                        <div className="form-warning">
                                            {this.state.errorInfo}
                                        </div>
                                    ): ''
                                }
                            </div>
                            <div className="padding10">
                                可转金额：{filter.toMoneyFormat(balance.avl_bal)}
                            </div>
                            <div className="padding10">
                                <button className= "sure-btn" disabled={this.state.transferDisabled} onClick={this.ValidatePassword.bind(this)}>确认转账</button>
                            </div>
                        </div>
                    )
                }
        	</div>
        )
    }
}


// -------------------redux react 绑定--------------------

function mapStateToProps(state) {
    return {
        walletinfo: state.walletinfo
    }
}

function mapDispatchToProps(dispatch) {
    return {
        walletinfoActions: bindActionCreators(walletInfoActionsFromOtherFile, dispatch)
    }
}
export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Transfer)
